<template>
    <div>
        <!--查询条件start --111s-->
        <el-form :inline="true" :model="query"  class="query-form"  size="small">
            <el-form-item>
                <el-button type="primary"  icon="el-icon-edit" @click.native="showDialogAddOrEdit(null,null)">添加
                </el-button>
            </el-form-item>
            <el-form-item class="query-form-item">
                <el-input v-model="query.searchtext" placeholder="请输入商品名称"  prefix-icon="el-icon-search"  @keyup.enter.native="onSubmit" clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-refresh"  @click="onRest"></el-button>
                <el-button type="primary" icon="el-icon-search"  @click="onSubmit">查询</el-button>
            </el-form-item>
        </el-form>
        <!--查询条件end-->
        <!--列表start --->
        <el-table ref="multipleTable"
                  v-loading="loading"
                  :data="list"
                  :header-cell-style="{background:'#F4F4F5',color:'#606266'}"
                  @selection-change="handleSelectionChange"
                  border>
            <el-table-column type="selection"  width="50" fixed />
            <el-table-column label="秒杀活动名称" prop="seckillname" width="150" align="center"/>
            <el-table-column label="开始时间"  with="300" :show-overflow-tooltip="true" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-time" v-if="scope.row.starttime!=null"></i>
                    <span v-if="scope.row.starttime!=null">{{ scope.row.starttime | formatDateStr('yyyy-MM-dd hh:mm:ss') }}</span>
                    <span v-else>无</span>
                </template>
            </el-table-column>
            <el-table-column label="结束时间" with="300" :show-overflow-tooltip="true" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-time"  v-if="scope.row.endtime!=null"></i>
                    <span v-if="scope.row.endtime!=null">{{ scope.row.endtime | formatDateStr('yyyy-MM-dd hh:mm:ss') }}</span>
                    <span v-else>无</span>
                </template>
            </el-table-column>
            <el-table-column label="秒杀产品" prop="commodityName" width="150" align="center"/>
            <el-table-column label="轮播图" prop="commodityIcon"  align="center" width="180">
                <template slot-scope="scope">
                    <el-popover v-if="scope.row.commodityIcon" placement="right" trigger="hover">
                        <img :src="scope.row.commodityIcon" style="width:400px;border-radius:3px;">
                        <img slot="reference" :src="scope.row.commodityIcon" style="max-height: 80px;max-width: 50px;border-radius:5px;">
                    </el-popover>
                    <span v-else>-</span>
                </template>
            </el-table-column>
            <el-table-column label="秒杀价格" prop="seckillprice" width="150" align="center"/>

            <el-table-column label="操作"  align="center">
                <template slot-scope="scope">
                    <el-button type="danger" size="mini"  @click.native="handleDel(scope.row.seckillid)">删除 </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--列表end --222e-->


        <!--全选删除start-->
        <div class="left-container">
            <el-button type="danger"
                       size="small"
                       @click="delGroup()">删除已选</el-button>
            <transition name="el-fade-in-linear">
                <el-button size="small"
                           @click="toggleSelection()"
                           v-show="cancelToggle">取消选择</el-button>
            </transition>
        </div>
        <!--全选删除end-->

        <!--分页模块start-->
        <el-pagination class="pagination-container"
                       background
                       :page-size="query.pageSize"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       layout="total,sizes,prev, pager, next, jumper"
                       :current-page="query.currentPage"
                       :page-sizes="[5,10, 20, 30, 50]"
                       :total="totalNumber"></el-pagination>
        <!--分页模块end-->

        <!--新增/编辑弹框start--333s-->
        <el-dialog :title="dialogAddOrEditName"
                   :visible.sync="dialogAddOrEdit"
                   width="50%"
                   :before-close="hideDialogAddOrEdit">
            <el-form :model="formData"
                     :rules="rules"
                     ref="ruleForm"
                     label-width="100px"
                     class="demo-ruleForm">
                <el-form-item class="query-form-item" label="秒杀名称：" prop="seckillname">
                    <el-input style="width: 50%" v-model="formData.seckillname"  placeholder="请输入秒杀名称" prefix-icon="el-icon-search" clearable></el-input>
                </el-form-item>
                <el-form-item label="开始时间：" prop="starttime">
                    <el-date-picker v-model="formData.starttime"  type="datetime" placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间：" prop="endtime">
                    <el-date-picker v-model="formData.endtime" type="datetime"  placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <el-form-item class="query-form-item" label="秒杀产品：">
                    <el-input style="width: 50%" v-model="commodityquery.searchtext"  placeholder="请输入商品名称" prefix-icon="el-icon-search" clearable></el-input>
                    <el-button style="margin-left:30px" type="primary"  icon="el-icon-search" @click="getCommodityList" :loading="queryLoading">查询</el-button>
                </el-form-item>
                <el-form-item label="商品：" prop="commodityid">
                    <el-select v-model="formData.commodityid"  placeholder="请选择" clearable >
                        <el-option v-for="item in commoditylist"
                                   :key="item.commodityid"
                                   :label="item.commodityname"
                                   :value="item.commodityid">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item class="query-form-item" label="秒杀价格：" prop="seckillprice">
                    <el-input style="width: 50%" v-model="formData.seckillprice"  placeholder="请输入秒杀价格" prefix-icon="el-icon-search" clearable></el-input>
                    元
                </el-form-item>
                <el-form-item class="query-form-item" label="秒杀详情：" prop="seckillintroduce">
                    <tinymce style="display: inline-block;width: 80%;" ref="content" v-model="formData.seckillintroduce" :height="500" />
                </el-form-item>
            </el-form>
            <span slot="footer"  class="dialog-footer">
                 <el-button @click="hideDialogAddOrEdit">取 消</el-button>
                 <el-button type="primary" :loading="formSumbitLoding"  @click="formSumbit">提 交</el-button>
             </span>

        </el-dialog>

    </div>
</template>
<script>

    import {
        getSeckillList,addOrUpdateSeckill,deleteSeckill
    } from "../../api/activityCommodity/seckillCommodity.js";
    import {getList } from "../../api/buscommodity/buscommodity.js";
    import Tinymce from "../../components/Tinymce/index";
    import {BASE_URL} from "../../config/app";
    /*用作表单的数据初始化*/
    const formJson = {
        seckillname:"",
        starttime:"",
        endtime:"",
        commodityid: "",
        seckillprice: "",
        seckillintroduce: ""
    };

    export default {
        components: {
            Tinymce
        },

        data() {
            return {
                uploadUrl: BASE_URL + '/goldendays-currency/tool/uploadpro', //上传图片
                uploadData: [],
                query: {
                    currentPage: 1,
                    searchtext: "",
                    pageSize: 10
                },
                commodityquery:{searchtext:"",},
                list: [], //列表集合
                commoditylist: [], //商品列表集合
                totalNumber: 0, //分页总页数
                loading: true, //列表加载
                queryLoading: false, //查询按钮
                formSumbitLoding: false, //表单提交加载
                cancelToggle: false, //列表是否全选
                multipleSelection: [], //多选集合
                dialogAddOrEdit: false, //新增或编辑弹框开关
                dialogAddOrEditName: "", //新增或编辑弹框名字
                formData: formJson, //新增或修改的对象
                rules: {
                    seckillname: {
                        required: true,
                        message: "请输入秒杀名称",
                        trigger: "blur"
                    },
                    starttime: {
                        required: true,
                        message: "请选择开始时间",
                        trigger: "blur"
                    },
                    endtime: {
                        required: true,
                        message: "请选择结束时间",
                        trigger: "blur"
                    },
                    commodityid: {
                        required: true,
                        message: "请选择商品",
                        trigger: "blur"
                    },
                    seckillprice:
                        [
                            { required: true, message: "请输入秒杀价格", trigger: "blur" },
                            { pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: "请输入合法的金额数字，最多两位小数", }
                        ],

                    seckillintroduce: {
                        required: true,
                        message: "请输入秒杀详情",
                        trigger: "blur"
                    },
                }
            };
        },

        methods: {
            /*获取列表事件*/
            getList() {
                this.loading = true;
                //   getTopList
                getSeckillList(this.query)
                    .then(response => {
                        if (response.code != 0) {
                            this.$message.error(response.message);
                            this.loading = false;
                            return false;
                        }
                        this.list = response.data.list || [];
                        this.totalNumber = response.data.totalNumber || 0;
                        setTimeout(() => {
                            this.loading = false;
                        }, 0.3 * 1000);
                    })
                    .catch(() => {
                        this.loading = false;
                        this.list = [];
                    });
            },

            /*新增或者编辑提交事件*/
            formSumbit() {
                //表单校验通过
                this.$refs["ruleForm"].validate(valid => {
                    if (valid) {
                        this.formSumbitLoding = true;
                        // this.formData = JSON.stringify(this.formData);
                        // this.formData={}
                        addOrUpdateSeckill(this.formData)
                            .then(response => {
                                this.formSumbitLoding = false;
                                if (response.code != 0) {
                                    this.$message.error(response.message);
                                    return false;
                                }
                                this.$message.success("操作成功");
                                this.hideDialogAddOrEdit();
                                // 加载表格数据
                                this.getList();
                            })
                            .catch(() => {
                                this.formSumbitLoding = false;
                            });
                    }
                });
                //new URLSearchParams(this.query)  提交数据格式不正确时可以转一下
            },
            getCommodityList(){
                this.queryLoading=true;
                let query= {
                    content:this.commodityquery.searchtext,
                    onshelfstatus: 1,
                    pageSize: 1000,
                    currentPage: 1,
                }
                getList(query).then(response => {
                    this.queryLoading=false;
                    if (response.code != 0) {
                        this.$message.error(response.message);
                        return false;
                    }
                    this.commoditylist = response.data.list || []
                }).catch(() => {
                    this.commoditylist = [];
                    this.queryLoading=false;
                })
            },
            /*列表查询条件事件*/
            onSubmit() {
                this.query.currentPage = 1;
                this.getList();
            },

            /*刷新*/
            onRest() {
                //刷新事件需要重置查询条件
                this.query = {
                    searchtext: "",
                    currentPage: 1,
                    pageSize: 5
                };
                this.getList();
            },

            //显示 查看弹框
            detailForm(index, row) {
                if (row !== null) {
                    this.dialogAddOrEdit = true;
                    this.formData = Object.assign({}, row);
                    let data = {
                        name: "",
                        url: ""
                    };
                    if (row.topcategorypic) {
                        this.uploadData = [];
                        let nameurl = row.topcategorypic;
                        data.url = nameurl;
                        data.name = nameurl.substring(nameurl.lastIndexOf("/") + 1);
                        this.uploadData.push(data);
                    }

                    this.dialogAddOrEditName = "编辑";
                }
            },

            /*显示 -新增或者编辑弹框*/
            showDialogAddOrEdit(index, row) {
                this.formData = Object.assign({}, formJson);
                if (row !== null) {
                    this.formData = Object.assign({}, row);
                }
                this.dialogAddOrEditName = "添加";
                //编辑
                if (index !== null) {
                    this.index = index;
                    this.dialogAddOrEditName = "编辑";
                }
                // 清空验证信息表单
                if (this.$refs["dataForm"]) {
                    this.$refs["dataForm"].clearValidate();
                }
                this.dialogAddOrEdit = true;

            },

            /*隐藏 -新增或编辑弹框*/
            hideDialogAddOrEdit() {
                this.dialogAddOrEdit = false;
                this.formData={};
                this.$refs.content.setContent("");
                this.commodityquery.searchtext="";
                //隐藏弹框时需要清除弹框内容
                if (this.$refs["ruleForm"]) {
                    this.$refs["ruleForm"].resetFields(); //清除formData表单
                    this.$refs["ruleForm"].clearValidate(); //清除表单验证
                }
                //如果上传文件，还需要清除文件列表
            },
            // 弹窗下拉选项变更获取商品

            /*点击页数*/
            handleCurrentChange(val) {
                this.query.currentPage = val;
                this.getList();
            },

            /*选择每页条数【10,20,30,40,50】*/
            handleSizeChange(val) {
                this.query.pageSize = val;
                this.getList();
            },
            /*取消全选事件*/
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row);
                    });
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },

            /*列表复选框选择事件*/
            handleSelectionChange(val) {
                this.multipleSelection = val;
                if (val == "") {
                    this.cancelToggle = false;
                    return;
                }
                this.cancelToggle = true;
            },

            /*全选删除事件*/
            delGroup() {
                var ids = this.multipleSelection.map(item => item.seckillid).join(); //获取所有选中行的id组成的字符串，以逗号分隔
                if (ids == "") {
                    this.$message({  message: "请先选择", type: "warning" });
                    return;
                }
                this.handleDel(ids);
            },

            /*单击删除事件*/
            handleDel(ids) {
                if (ids) {
                    this.$confirm("确认要删除吗?", "提示", {
                        type: "warning"
                    }).then(() => {
                        this.loading = true;
                        var params = new URLSearchParams();
                        params.append("seckillid", ids);
                        deleteSeckill(params)
                            .then(response => {
                                this.loading = false;
                                if (response.code) {
                                    this.$message.error(response.message);
                                    return false;
                                }
                                this.$message.success("删除成功");
                                // 刷新数据
                                //this.list.splice(index, 1);
                                this.getList();
                            })
                            .catch(() => {
                                this.loading = false;
                            });
                    })
                        .catch(() => {
                            this.$message.warning("已取消");
                        });
                }
            }
        },
        created() {
            this.getList();
        }
    };
</script>
